package com.itwenke.springbootdemo.shirowebssm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1024);
        this.setCredentialsMatcher(matcher);
    }

    /**
     * 用户认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户名
        String username = (String) authenticationToken.getPrincipal();

        // 判断用户名（非空）
        if(username == null || username.equals("")){
            // 返回null，默认抛出一个异常：org.apache.shiro.authc.UnknownAccountException
            return null;
        }

        // 根据用户名查询用户
        User user = this.findUserByUsername(username);

        // 判断用户是否为null
        if(user == null) {
            return null;
        }

        // 声明 SimpleAuthenticationInfo 对象，并填充用户信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(),"CustomRealm");

        // 设置盐
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));

        return simpleAuthenticationInfo;
    }

    /***
     * 授权认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取认证用户
        User user = (User) principalCollection.getPrimaryPrincipal();

        // 根据用户获取当前用户拥有的角色
        Set<String> roleSet = this.findRolesByUser(user);

        // 根据用户拥有的角色查询权限信息
        Set<String> permSet = this.findPermsByRoleSet(roleSet);

        // 声明 SimpleAuthorizationInfo 对象，并填充角色信息和权限信息
        SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
        simpleAuthenticationInfo.setRoles(roleSet);
        simpleAuthenticationInfo.setStringPermissions(permSet);

        return simpleAuthenticationInfo;
    }

    /**
     * 生成加盐的MD5密码
     */
    public static void main(String[] args) {
        System.out.println(new Md5Hash("test", "abcdefg123456", 1024));
    }

    /**
     * 模拟数据库操作
     */
    private User findUserByUsername(String username) {
        if("admin".equals(username)){
            User user = new User();
            user.setId(1);
            user.setUsername("admin");
            user.setPassword("3e48d56a6fc20c50f589f562cdf20451");
            user.setSalt("abcdefg123456");
            return user;
        }
        return null;
    }

    /**
     * 模拟数据库操作
     */
    private Set<String> findRolesByUser(User user) {
        Set<String> set = new HashSet<>();
        set.add("超级管理员");
        set.add("运营管理员");
        return set;
    }

    /**
     * 模拟数据库操作
     */
    private Set<String> findPermsByRoleSet(Set<String> roleSet) {
        Set<String> set = new HashSet<>();
        set.add("user:add");
        set.add("user:update");
        return set;
    }
}
